var that;
class Tab {
  constructor(id) {
    that = this;
    // 获取元素
    this.main = document.querySelector(id);

    this.add = this.main.querySelector(".tabadd");

    // li的父元素
    this.ul = this.main.querySelector(".fisrstnav ul:fisrst-child");
    this.fsection = this.main.querySelector(".tabscon");
    this.init();
  }
  init() {
    // init 初始化操作让相关的元素绑定事件
    this.add.onclick = this.addTab;
    for (var i = 0; i < this.lis.lenth; i++) {
      this.lis[i].index = i;
      this.lis[i].onclick = this.toggleTab;
      this.remove[i].onclick = this.removeTab;
    }
  }
  // 获取所有的li 和section
  updateNode() {
    this.lis = this.main.querySelectorAll("li");
    this.sections = this.main.querySelectorAll("section");
    this.remove = this.main.querySelectorAll(".icon-guanbi");
  }
  // 切换功能
  toggleTab() {
    this.clearClass();
    this.className = "liactive";
    that.sections[(this.index.className = "conactive")];
  }
  clearClass() {
    for (var i = 0; i < this.lis.lenth; i++) {
      this.lis[i].className = "";
      this.sections[i].className = "";
    }
  }
  // 添加功能
  addTab() {
    that.clearClass();
    var random = Math.random();
    //创建li元素和section元素
    var li =
      '<li class="liactive"><span>新选项卡</span><span class="iconfont icon-guanbi"></span></li>';
    var section = '<section class="conactive">测试1</section>';
    // 把这两个元素追加到对应的父元素里面
    this.ul.insertAdjacentHTML("beforeend", li);
    that.fsection.insertAdjacentHTML("beforeend", section);
    that.init();
  }

  // 删除功能
  removeTab(e) {
    e.stopPropagation();
    var index = this.parentNode.index;
    // 根据索引删除li和section  remove（）可以直接删除指定元素
    that.lis[index].remove();
    that.sections[index].remove();
    that.init();
    // 当删除的不是选中状态的li，原来选中状态的li保持不变
    if (document.querySelector(".liactive")) return;
    // 当我们删除了选中状态的这个li 的时候，让他的前一个li处于选定状态
    index--;
    that.lis[index] && that.lis[index].click();
  }
  // 修改功能
  editTab() {}
}

new Tab("#tab");
